package com.deyuanyun.pic.settings.support.utils;

import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.DigestUtils;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.HttpClientUtil;
import com.deyuanyun.pic.common.util.XMLUtils;
import com.deyuanyun.pic.settings.controller.dto.SMSMessageVO;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.domain.base.SmsSendLog;
import com.deyuanyun.pic.settings.mapper.base.SmsSendLogMapper;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import com.deyuanyun.pic.settings.task.StaticConsts;

/**
 * @author chace.cai   xu
 * @description  短信发送
 * @date 2016/4/1
 */
public class SMSUtils {
    static Logger logger=Logger.getLogger(SMSUtils.class);
   /* public static String SMS_SEND_URL="http://hyt.uewang.net/v2sms.aspx";
    public static String SMS_QUERY_URL="http://hyt.uewang.net/v2statusApi.aspx";
    public static String USERID="68";
    public static String ACCOUNT="scdyygd";
    public static String PWD="123456qaz";
    public static String login_m="尊敬的客户， 您正在登录管道专家服务，您的验证码是{0}，请勿泄露，感谢您使用。如有异常登录，请联系客服。";
    public static String reg_m="尊敬的客户，您正在注册管道专家服务，您的注册验证码是{0}，请勿泄露，感谢您使用。";
    public static String findPassWord_m="尊敬的客户，您正在重置密码，本次操作验证码是{0}，请勿泄露，感谢您使用。";*/

    public static String SMS_SEND_URL="";
    public static String SMS_QUERY_URL="";
    public static String USERID="";
    public static String ACCOUNT="";
    public static String PWD="";
    public static String login_m="";
    public static String reg_m="";
    public static String findPassWord_m="";
    public static String tryOut_m="";

    /**
     * 发送短信
     * @param messageVO
     * @return
     * @throws ParseException
     */
    public static String senSMS(SMSMessageVO messageVO) throws ParseException {

        if (StringUtils.isBlank(SMS_SEND_URL)){
            logger.error("短信配置参数没有获取到");
            return "";
        }

        String phone=messageVO.getPhone();
        String smessage=messageVO.getMessage();
        if (StringUtils.isBlank(phone)||StringUtils.isBlank(smessage)){
            return "err>";
        }
        if (!com.deyuanyun.pic.common.util.StringUtils.isMobile(phone)){
            return "err>>";
        }

        //限制发送频率
        String p1= TempStoreDataSupport.pullData("sms_"+messageVO.getPhone());
        if (StringUtils.isNotBlank(p1)){
            logger.error(messageVO.getPhone()+"发送频率太快!!!");
            return "";
        }
        TempStoreDataSupport.pushDataByTimeMinute("sms_"+messageVO.getPhone(),new Date().toString(),2);

        Map<String,String> map=new HashMap();
        String time= DateUtil.DateToStringYMDHMS(new Date());
        String sin=makeSign(time);
        map.put("action","send");
        map.put("userid",USERID);
        map.put("timestamp",time);
        map.put("sign",sin);
        map.put("mobile",phone);
        map.put("content",smessage);
        
        SmsSendLog SmsSendLog=new SmsSendLog();
        SmsSendLog.setContent(messageVO.getMessage());
        SmsSendLog.setMobile(messageVO.getPhone());
        SmsSendLog.setSendType(messageVO.getType());
        SmsSendLog.setSendTime(new Date());
        String logId=insertSMSLog(SmsSendLog);
        SmsSendLog.setId(logId);
        map.put("sendTime","");
        try {
            /*if (true){
                System.out.println(">>>>>send>"+messageVO.getPhone());//todo 暂时屏蔽了，避免误发浪费
                return "";}*/
            
            String res = HttpClientUtil.httpPostRequest(SMS_SEND_URL,map);
            /*String res ="<?xml version=\"1.0\" encoding=\"utf-8\" ?><returnsms>\n" +
                    " <returnstatus>Success</returnstatus>\n" +
                    " <message>ok</message>\n" +
                    " <remainpoint>159</remainpoint>\n" +
                    " <taskID>1230</taskID>\n" +
                    " <successCounts>1</successCounts></returnsms>";*/
            String returnstatus= XMLUtils.getSpecifyElementTextAllInOne(res,"returnstatus");
            String message= XMLUtils.getSpecifyElementTextAllInOne(res,"message");
            String remainpoint= XMLUtils.getSpecifyElementTextAllInOne(res,"remainpoint");//余额
            String taskID= XMLUtils.getSpecifyElementTextAllInOne(res,"taskID");
            String successCounts= XMLUtils.getSpecifyElementTextAllInOne(res,"successCounts");

            //记录日志
            SmsSendLogMapper SmsSendLogMapper= SpringAppliction.getBean(SmsSendLogMapper.class);
            SmsSendLog.setMobile(null);
            SmsSendLog.setContent(null);
            SmsSendLog.setSendType(null);
            SmsSendLog.setUpdateDate(new Date());
            SmsSendLog.setStatus(returnstatus);//提交成功或者失败
            SmsSendLog.setTaskCode(taskID);
            SmsSendLog.setResultContent(res);
            SmsSendLogMapper.updateByPrimaryKeySelective(SmsSendLog);
            System.out.println(res);
        } catch (Exception e) {
            logger.error(">>发送短信报错"+messageVO.getPhone(),e);
            SmsSendLogMapper SmsSendLogMapper= SpringAppliction.getBean(SmsSendLogMapper.class);
            SmsSendLog.setMobile(null);
            SmsSendLog.setContent(null);
            SmsSendLog.setSendType(null);
            SmsSendLog.setUpdateDate(new Date());
            SmsSendLog.setStatus("Timeout");//提交成功或者失败
            SmsSendLog.setTaskCode(null);
            SmsSendLog.setResultContent("网络异常 :" + e.getMessage());
            SmsSendLogMapper.updateByPrimaryKeySelective(SmsSendLog);
            return "err";
        }
        return "";
    }

    /**
     * 获取状态报告
     * @throws Exception
     */
    public static void getSMSStatus()throws Exception{
        Map<String,String> map=new HashMap();
        String time= DateUtil.DateToStringYMDHMS(new Date());
        String sin=makeSign(time);
        map.put("action","query");
        map.put("userid",USERID);
        map.put("timestamp",time);
        map.put("sign",sin);
        String res = HttpClientUtil.httpPostRequest(SMS_QUERY_URL,map);
        System.out.println(res);
    }

    private static String makeSign(String time){
        String sin= DigestUtils.md5DigestAsHex((ACCOUNT+PWD+time).getBytes());
        return sin;
    }

    /**
     * 生成登录时的验证码
     * @return
     */
    public static String makeLoginCaptchaMsg(String phone){
        //HttpServletRequest request = RequestResponseContext.getRequest();
        String loginCode = RandomStringUtils.randomNumeric(6);
        TempStoreDataSupport.pushDataByTimeMinute(StaticConsts.PM_LOGIN_CODE+phone,loginCode,5);
        //request.getSession().setAttribute(StaticConsts.PM_LOGIN_CODE,loginCode);
        String m= MessageFormat.format(login_m,loginCode);
        return m;
    }

    /**
     * 生成找回密码时的验证码
     * @return
     */
    public static String makeFPWCaptchaMsg(String phone){
        //HttpServletRequest request = RequestResponseContext.getRequest();
        String loginCode = RandomStringUtils.randomNumeric(6);
        TempStoreDataSupport.pushDataByTimeMinute(StaticConsts.PM_PW_CODE+phone,loginCode,StaticConsts.PM_PW_CODE_TIME);
        //request.getSession().setAttribute(StaticConsts.PM_LOGIN_CODE,loginCode);
        String m= MessageFormat.format(findPassWord_m,loginCode);
        return m;
    }

    /**
     * 注册时候的验证码
     * @return
     */
    public static String makeRegCaptchaMsg(String phone){
       // HttpServletRequest request = RequestResponseContext.getRequest();
        String regCode = RandomStringUtils.randomNumeric(6);
        TempStoreDataSupport.pushDataByTimeMinute(StaticConsts.PM_REG_CODE+phone,regCode,StaticConsts.PM_REG_CODE_TIME);
        //request.getSession().setAttribute(StaticConsts.PM_REG_CODE,regCode);
        String m= MessageFormat.format(reg_m,regCode);
        return m;
    }


    /**
     * 发送试用信息的短信
     * @return
     */
    public static String makeTryOutMsg(String phone){
       // HttpServletRequest request = RequestResponseContext.getRequest();
        //String regCode = RandomStringUtils.randomNumeric(6);
        //TempStoreDataSupport.pushDataByTimeMinute(StaticConsts.PM_REG_CODE+phone,regCode,StaticConsts.PM_REG_CODE_TIME);
        //request.getSession().setAttribute(StaticConsts.PM_REG_CODE,regCode);
        String m= MessageFormat.format(tryOut_m,phone);
        return m;
    }


    private static String insertSMSLog(SmsSendLog SmsSendLog){
        String id=CommonUtil.getUUID();
        SmsSendLog.setId(id);
        SmsSendLog.setDeleted((short) 0);
        SmsSendLog.setCreateDate(new Date());
        UserSessionVO sessionVO= SessionCacheSupport.getSessionVO();
        if (sessionVO!=null){
            SmsSendLog.setCreateUser(sessionVO.getId());
        }

        SmsSendLogMapper SmsSendLogMapper= SpringAppliction.getBean(SmsSendLogMapper.class);
        SmsSendLogMapper.insertSelective(SmsSendLog);

        return id;
    }


    public static void main(String[] args) throws Exception {
        getSMSStatus();
    }
}
